﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO;
using Microsoft.Office.Interop.Word;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.ShowDialog();
            this.textBox_input.Text = path.SelectedPath;
            this.inputPath = path.SelectedPath;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.ShowDialog();
            this.textBox_output.Text = path.SelectedPath;
            this.outputPath = path.SelectedPath;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            iterateDirectory(this.inputPath, this.outputPath);
            MessageBox.Show("转换完成");
        }

        private void iterateDirectory(string folderPath, string outputFolder)
        {
            DirectoryInfo theFolder = new DirectoryInfo(folderPath);
            foreach (FileInfo nextFile in theFolder.GetFiles())
            {
                if (nextFile.Extension.Equals(".doc") || nextFile.Extension.Equals(".docx"))
                {
                    string inputFileFullName = nextFile.FullName;
                    int lastDot = nextFile.Name.LastIndexOf('.');
                    string outputFileFullName = outputFolder + "\\" + nextFile.Name.Substring(0, lastDot) + ".pdf";
                    Console.WriteLine(inputFileFullName);
                    Console.WriteLine(outputFileFullName);
                    this.MyConvert(inputFileFullName, outputFileFullName);
                }
            }
            foreach (DirectoryInfo nextFolder in theFolder.GetDirectories())
            {
                iterateDirectory(nextFolder.FullName, outputFolder);
            }
        }

        private void MyConvert(string inputFileName, string OutputFileName)
        {
            Microsoft.Office.Interop.Word.ApplicationClass app = new Microsoft.Office.Interop.Word.ApplicationClass();
            Microsoft.Office.Interop.Word.Document doc = null;
            try
            {
                doc = app.Documents.Open(inputFileName);
                doc.ExportAsFixedFormat(OutputFileName, WdExportFormat.wdExportFormatPDF);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }
            finally
            {
                doc.Close();
            }

        }

        private string inputPath;
        private string outputPath;
    }
}
